package com.lxl;

import com.lxl.config.SystemConfig;
import com.lxl.filter.FormatFilter;
import com.lxl.servlet.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.DispatcherType;
import java.net.Inet4Address;
import java.util.EnumSet;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EmbeddedJettyLauncher {
    private static Logger LOGGER;
    static{
        LOGGER = Logger.getLogger(Launcher.class.getName());
        LOGGER.setLevel(Level.INFO);
    }

    public static void startJetty() throws Exception {
        LOGGER.info("Web environment is being initialized.");

        Server server = new Server(SystemConfig.SERVER_NIO_PORT);

        ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        servletContextHandler.setContextPath("/funso");
        servletContextHandler.addFilter(FormatFilter.class, "/*",EnumSet.of(DispatcherType.REQUEST));
        servletContextHandler.addServlet(new ServletHolder(new TestServlet()), "/test");
        servletContextHandler.addServlet(new ServletHolder(new ShortJobServlet()), "/shortJob");
        servletContextHandler.addServlet(new ServletHolder(new ShortTransServlet()), "/shortTrans");
        servletContextHandler.addServlet(new ServletHolder(new LongJobServlet()), "/longJob");
        servletContextHandler.addServlet(new ServletHolder(new LongTransServlet()), "/longTrans");
        servletContextHandler.addServlet(new ServletHolder(new UploadServlet()), "/upload");
        servletContextHandler.addServlet(new ServletHolder(new DeleteServlet()), "/delete");
        servletContextHandler.addServlet(new ServletHolder(new DownloadServlet()), "/download");

        server.setHandler(servletContextHandler);

        LOGGER.info("The entrance: http://" + Inet4Address.getLocalHost().getHostAddress()
                + ":" + SystemConfig.SERVER_NIO_PORT
                + SystemConfig.ETL_CONTEXT_NAME
                + "/" + "[TASK_NAME]");
        server.start();
        server.join();
    }
}
